package 临时工具.常山;

import com.alibaba.fastjson.JSON;
import org.springframework.util.DigestUtils;

import java.util.Map;
import java.util.TreeMap;

public class SignUtil {

    public static void main(String[] args) {
        // 示例参数
        String accessKey = "330822101";
        String secretKey = "your_secret_key";
        long timestamp = System.currentTimeMillis();

        // 请求参数
        Map<String, Object> requestParams = new TreeMap<>();
        requestParams.put("param1", "value1");
        requestParams.put("param2", "value2");

        // 生成签名
        String sign = generateMD5Signature(requestParams, timestamp,accessKey, secretKey);

        // 输出签名
        System.out.println("Generated Sign: " + sign);
    }

    // 生成MD5签名
    public static String generateMD5Signature( Map<String, Object> requestParams, long timestamp,String accessKey, String secretKey) {
        // 构建按字母升序排列的参数字符串
        String sortedParams = buildSortedParams( requestParams);

        // 构建待签名字符串
        String stringSignTemp = "AccessKey=" + accessKey + "&" + sortedParams + "&timestamp=" + timestamp + "&SecretKey=" + secretKey;
        System.out.println("stringSignTemp: " + stringSignTemp);
        // 计算MD5并转为大写形式
        String sign = DigestUtils.md5DigestAsHex(stringSignTemp.getBytes()).toUpperCase();
        System.out.println("Generated Sign: " + sign);
        return sign;
    }

    // 构建按字母升序排列的参数字符串
    private static String buildSortedParams( Map<String, Object> requestParams) {
        TreeMap<String, Object> sortedParams = new TreeMap<>();
        sortedParams.putAll(requestParams);
        StringBuilder paramsBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
            if (entry.getKey().equals("valveList")){
                paramsBuilder.append(entry.getKey()).append("=").append(JSON.toJSONString(entry.getValue())).append("&");
            }else {
                paramsBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            }


        // 删除最后一个"&"
        paramsBuilder.deleteCharAt(paramsBuilder.length() - 1);

        return paramsBuilder.toString();
    }


}
